package com.mt.vsphere.core.zhu.security;

import com.mt.vsphere.core.util.SpringContextUtil;
import com.mt.vsphere.core.util.TokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.Optional;

public class AuthTokenUtil {
    private static Logger logger = LoggerFactory.getLogger(AuthTokenUtil.class);


    //是否需要认证的URI
    public static boolean authRequest(HttpServletRequest request, HttpServletResponse httpServletResponse) throws IOException {
        TokenUtil tokenUtil = (TokenUtil) SpringContextUtil.getBean(TokenUtil.class);

        String requestURI = request.getRequestURI();
        Map<String,AuthRole> map = ((AuthScanner) SpringContextUtil.getBean(AuthScanner.class)).getUrlRoleMap();
        AuthRole authRole = Optional.ofNullable(map.get(requestURI)).orElse(AuthRole.Anonymous);
        String token;
        switch (authRole){
            case User:
                token = (request).getHeader("token");
                if (token == null || !tokenUtil.verifyUser(token,(request)) ){
                    authFail(httpServletResponse);
                    return false;
                }
                break;
            case Writer:
                token = (request).getHeader("token");
                if (token == null || !tokenUtil.verifyWriter(token,(request)) ){
                    authFail(httpServletResponse);
                    return false;
                }
                break;
            case Admin:
                token = (request).getHeader("token");
                if (token == null || !tokenUtil.verifyAdmin(token)){
                    authFail(httpServletResponse);
                    return false;
                }
                break;
            case AnonymousOrLogin:
                token = (request).getHeader("token");
                if (token != null  ){
                    tokenUtil.verifyUser(token,(request));
                }
                break;
            default:
        }
        return true;
    }



    private static void authFail(HttpServletResponse res) throws IOException {
        logger.error("请求失败，token认证不成功");
        res.setHeader("Content-Type", "application/json;charset=UTF-8");
        String rtnStr = "{\n" +
                "    \"code\": 1,\n" +
                "    \"status\": 401,\n" +
                "    \"message\": \"无权限\"\n" +
//                "    \"data\": []\n" +
                "}";
        res.getOutputStream().write(rtnStr.getBytes());
        res.getOutputStream().flush();
        res.getOutputStream().close();
        }
        
}
